<template>
    <div class="sendPwdBox">
        <Modal
            v-model="isVisible"
            :mask-closable="false"
            :width="800"
            title="密码发放"
            @on-visible-change="onVisibleChange"
            class-name="license-modal">

            <Form ref="addPwdForm" :model="formItem" :rules="formRules" :label-width="150" :show-message="false">
                <Row class="add-pwd-line" type="flex" align="middle">
                    <Col span="12" class="pwd-padd">
                        <FormItem label="房间号：" class="add-pwd-form-item">
                            {{ roomName }}
                        </FormItem>
                    </Col>

                    <Row v-if="Object.keys(this.renterDetail) && this.renterDetail.can_relate_tenant && !this.renterDetail.is_show_public_room" style="width: 100%">
                        <Col span="12" class="pwd-padd">
                            <FormItem label="租客：" class="add-pwd-form-item">
                                {{ this.renterDetail.tenants[0].tenant_name + ` ` + this.renterDetail.tenants[0].tenant_phone }}
                            </FormItem>
                        </Col>

                        <Col span="12" class="pwd-padd">
                            <FormItem label="租约时间：" class="add-pwd-form-item">
                                {{ this.renterDetail.tenants[0].lease_range[0] | timeFilter }}{{` - `}}{{ this.renterDetail.tenants[0].lease_range[1] | timeFilter }}
                            </FormItem>
                        </Col>
                    </Row>
                    <!-- <Col span="12" v-if="roomName != '公区'">
                        <FormItem label="外门密码：" class="add-pwd-form-item">
                            <Checkbox v-model="isAddPwdOutLock">同时发放外门锁密码</Checkbox>
                        </FormItem>
                    </Col> -->
                    <!-- <Col span="24">
                        <FormItem label="关联租客：" class="add-pwd-form-item">
                            <Select
                                v-model="linkTenant"
                                clearable
                                placeholder="请选择租客"
                                style="width: 210px;margin-right: 20px;">
                                <Option v-for="item in tenantArr" :value="item.id" :key="item.id">{{ item.name }}</Option>
                            </Select>
                            注：<b>关联租客后，租客退租，该授权同步失效</b>
                        </FormItem>
                    </Col> -->
                </Row>

                <Row class="add-pwd-line add-pwd-pad" type="flex" align="middle">
                    <Col span="21">
                        <FormItem label="被授权人姓名：" prop="name" class="add-pwd-form-item">
                            <Input v-model.trim="formItem.name" placeholder="被授权人姓名" :maxlength="50" clearable></Input>
                        </FormItem>
                    </Col>
                    <Col span="21">
                        <FormItem label="被授权人电话：" prop="phone" class="add-pwd-form-item">
                            <Input v-model.trim="formItem.phone" placeholder="被授权人电话" clearable>
                                <Select v-model="formItem.country_code" slot="prepend" style="width: 110px">
                                    <Option v-for="item in CountryCodes" :key="item.code" :value="item.code">{{item.country}}</Option>
                                </Select>
                            </Input>
                        </FormItem>
                    </Col>
                    <Col span="21" v-if="Object.keys(this.renterDetail) && this.renterDetail.tenants && this.renterDetail.tenants.length">
                        <FormItem label="关联租客：" style="margin-bottom: 0px;">
                            <Select v-model="tenantLeaseId">
                                <Option v-for="(item, index) in Tenants" :key="index" :value="item.lease_id">{{item.tenant_name}}</Option>
                            </Select>
                            <p>注：<b>关联租客后，租客退租，该授权同步失效</b></p>
                        </FormItem>
                    </Col>
                </Row>

                <Row type="flex" align="middle" style="padding-top: 20px;">
                    <Col span="12">
                        <FormItem label="密码有效期：" prop="pwdPeriodType" style="margin-bottom:15px" class="add-pwd-form-item">
                            <Select v-model="formItem.pwdPeriodType" @on-change="selectPwdPeriod">
                                <Option v-for="item in pwdPeriodTypes" :value="item.type" :key="item.type">{{ item.text }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="12" style="margin-bottom:15px;padding-left:20px">
                        <Checkbox v-model="is_send_active_pwd" v-if="lockIsOnline">发放离线密码</Checkbox>
                        <Checkbox v-model="is_send_location">短信携带公寓信息</Checkbox>
                    </Col>
                </Row>

                <FormItem label="">
                    <Row>
                        <Col span="9">
                            <FormItem prop="pwdStartTime">
                                <Input v-if="sendOfflinePwd" disabled :value="new Date(formItem.pwdStartTime).Format('YYYY-MM-DD HH:mm')"></Input>
                                <DatePicker v-else type="datetime" v-model="formItem.pwdStartTime" format="yyyy-MM-dd HH:mm" placeholder="开始时间" style="width: 100%" :options="pwdStartTimeOptions" @on-ok="selectStartTime"></DatePicker>
                            </FormItem>
                        </Col>
                        <Col span="2" style="text-align: center">-</Col>
                        <Col span="9"> 
                            <FormItem prop="pwdEndTime">
                                <DatePicker type="datetime" v-model="formItem.pwdEndTime" format="yyyy-MM-dd HH:mm" placeholder="结束时间" style="width: 100%" :options="pwdEndTimeOptions"></DatePicker>
                            </FormItem>
                        </Col>
                        <Col span="24" v-if="sendOfflinePwd">
                            <p style="color:#f00">当前下发密码为离线密码, 有效期不可以超过一年</p>
                        </Col>
                    </Row>
                </FormItem>

                <Row type="flex" align="middle" v-if="sendOfflinePwd">
                    <Col>
                        <FormItem label="使用角色：" prop="userGroup">
                            <RadioGroup v-model="formItem.userGroup">
                                <Radio :label="1">租客</Radio>
                                <Radio :label="2">员工</Radio>
                            </RadioGroup>
                            <p>注：员工离线密码可在门锁上删除租客密码。</p>
                        </FormItem>
                    </Col>
                </Row>

            </Form>
            
            <div slot="footer">
                <Button type="ghost" size="large" @click="hideModal">取消</Button>
                <Button type="primary" size="large" @click="sendPwd('addPwdForm')">确定</Button>
            </div>
            
        </Modal>
    </div>
</template>

<script>
import debounce from 'lodash/debounce'
import dayjs from 'dayjs'
import { RoomTypeEnum, DeviceTypeEnum, CountryCodes } from '@/libs/const'
import util from '@/libs/util'
import validate from '@/libs/validate'
import { http, api } from '@/libs/http'

export default {
  name: 'sendPwd',
  props: {
    lockDetail: {
      type: Object,
      default: null
    },
    visible: {
      type: Boolean,
      default: false
    },
    renterDetail: {
      type: Object,
      default: {}
    },
    isForce: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      Tenants: [],
      tenantLeaseId: -1,
      is_send_location: false,
      is_send_active_pwd: false,
      RoomTypeEnum: RoomTypeEnum,
      DeviceTypeEnum: DeviceTypeEnum,
      lockHasgateWay: true, // 该门锁是否含有网关,默认为包含
      passwordPromptFlag: 3, // 密码提示变量，可为 0 1 2 3,对应computed里面的passwordPrompt

      authTypes: [{ type: 1, text: '租客' }, { type: 2, text: '保洁' }, { type: 3, text: '装修' }, { type: 4, text: '其他' }],
      pwdPeriodTypes: [
        { type: 0, text: '请选择时长' },
        { type: 0.5, text: '半个月' },
        { type: 1, text: '一个月' },
        { type: 3, text: '三个月' },
        { type: 6, text: '六个月' },
        { type: 12, text: '十二个月' },
        { type: -1, text: '自定义' }
      ],
      tenantArr: [], // 可关联租客列表
      linkTenant: '', // 关联租客

      isAddPwdOutLock: false,
      formItem: {
        name: '',
        phone: '',
        authType: 1,
        pwdPeriodType: 0,
        pwdStartTime: dayjs().toDate(),
        pwdEndTime: '',
        country_code: '86',
        userGroup: 1
      },
      formRules: {
        name: [{ required: true, message: '被授权人不能为空', trigger: 'change' }],
        phone: [{ required: true, message: '账号不能为空', trigger: 'change' }, {
          required: true,
          message: '账号格式错误',
          validator: validate.validPhone
        }],
        pwdStartTime: [{ required: true, type: 'date', message: '不能为空', trigger: 'blur' }],
        pwdEndTime: [{ required: true, type: 'date', message: '不能为空', trigger: 'blur' }]
      },
      CountryCodes
    }
  },
  watch: {
    tenantLeaseId (value) { // 选择的租客
      if (value !== -1) {
        const { lease_range } = this.renterDetail.tenants.find((tenant) => (tenant.lease_id === value))

        this.formItem.userGroup = 1
        this.$set(this.formItem, 'pwdStartTime', new Date(lease_range[0]))
        this.$set(this.formItem, 'pwdEndTime', this.sendOfflinePwd ? dayjs(Math.min(dayjs(lease_range[1]).valueOf(), dayjs(lease_range[0]).add(1, 'year').valueOf())).toDate() : new Date(lease_range[1]))
      } else {
        this.$set(this.formItem, 'pwdEndTime', '')
      }
    },

    is_send_active_pwd (newVal) {
      if (newVal) {
        this.formItem.pwdEndTime = ''
        this.formItem.pwdStartTime = dayjs().toDate()
        this.formItem.userGroup = 1
      }
    },
    renterDetail (value) {
      if (Object.keys(value)) {
        this.Tenants = [...value.tenants, {
          tenant_name: '不关联',
          lease_id: -1
        }]

        if (value.can_relate_tenant && !value.is_show_public_room) {
          this.tenantLeaseId = value.tenants[0] && value.tenants[0].lease_id
        } else {
          this.tenantLeaseId = -1
        }
      }
    },

    'formItem.country_code' (value) {
      this.$set(this.formRules, 'phone', [{ required: true, message: '账号不能为空', trigger: 'change' }, {
        required: true,
        message: '账号格式错误',
        validator: value === '86' ? validate.validPhone : validate.validEnglishPhone
      }])
    },
    'formItem.userGroup' (value) {
      if (value === 2) {
        this.tenantLeaseId = -1
      } else {
        if (Object.keys(this.renterDetail) && this.renterDetail.can_relate_tenant && !this.renterDetail.is_show_public_room) {
          this.tenantLeaseId = this.Tenants[0] && this.Tenants[0].lease_id
        }
      }
    }
  },
  computed: {
    isVisible: {
      get: function () {
        return this.visible
      },

      set: function (val) {
        this.$emit('on-close', val)
      }
    },
    roomName () {
      return this.lockDetail.roomName
    },
    passwordPrompt () {
      let flag = this.passwordPromptFlag

      if (flag === 0) return '无网关门锁仅能发放离线密码，离线密码仅限当天使用'
      else if (flag === 1) return '门锁离线仅能发放离线密码，离线密码仅限当天使用'
      else if (flag === 2) return '当前设备离线，密码无法生效。建议恢复设备在线或使用离线密码'
      else return ''
    },

    lockIsOnline () { // 门锁是否在线, 默认为不在线
      if (this.renterDetail && this.renterDetail.can_send_online_password) {
        return true
      } else {
        return false
      }
    },

    // 是否发放离线密码
    sendOfflinePwd () { // 只有在门锁在线而且不选择下发激活码密码才出现
      if (this.lockIsOnline && !this.is_send_active_pwd) {
        return false
      } else {
        return true
      }
    },

    addLicencesStartTime () {
      // 开始时间，禁选范围（全禁选）发放离线密码时
      return {
        disabledDate: date => {
          return date && date.valueOf() < Date.now() - 86400000
        }
      }
    },

    addLicencesEndTime () {
      // 结束时间，禁选范围
      return {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000
        }
      }
    },

    pwdStartTimeOptions () {
      return {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000
        }
      }
    },

    pwdEndTimeOptions () { // 如果下发离线密码结束时间不能超过一年
      return {
        disabledDate: (date) => {
          return this.sendOfflinePwd ? date && (date.valueOf() < Date.now() - 86400000 || date.valueOf() > dayjs(this.formItem.pwdStartTime).add(1, 'year').valueOf()) : date && date.valueOf() < Date.now() - 86400000
        }
      }
    }
  },
  mounted () {
    util.log('lockDetail', this.lockDetail)
    this.$nextTick(() => {
      let maskArr = document.getElementsByClassName('license-modal')
      let len = maskArr.length
      for (let i = 0; i < len; i++) {
        maskArr[i].parentNode.getElementsByClassName('ivu-modal-mask')[0].style.zIndex = 1004
      }
    })
  },

  filters: {
    timeFilter (time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },

  methods: {
    changeTenant (tenant) {
      console.log('tenant', tenant)
    },

    hideModal () {
      this.isVisible = false
    },

    selectPwdType (type) {
      this.formItem.pwdStartTime = dayjs().toDate()
      this.formItem.pwdEndTime = ''
      this.formItem.pwdPeriodType = 0
    },
    selectPwdPeriod (type) {
      this.formItem.pwdStartTime = dayjs().toDate()

      switch (type) {
        case -1:
          this.formItem.pwdEndTime = ''
          break
        case 0.5:
          this.formItem.pwdEndTime = dayjs()
            .add(15, 'days')
            .toDate()
          break
        case 1:
        case 3:
        case 6:
        case 12:
          this.formItem.pwdEndTime = dayjs()
            .add(type, 'months')
            .toDate()
          break
      }
    },

    selectStartTime (e) {
      let formItem = this.formItem
      if (formItem.pwdEndTime <= formItem.pwdStartTime) {
        formItem.pwdEndTime = ''
      }
    },

    sendPwd: debounce(function (name) {
      this.$refs[name].validate(valid => {
        if (!valid) {
          this.$Message.error('请完整填写表单数据')
          return
        }
        const formItem = this.formItem

        if (formItem.pwdEndTime <= formItem.pwdStartTime) {
          this.$Message.info('结束时间需大于开始时间')
          return
        }
        const phoneReg = /^1\d{10}$/
        if (formItem.country_code === '86' && !phoneReg.test(formItem.phone)) {
          this.$Message.info('手机号格式错误')
          return
        }

        let startTime = dayjs(formItem.pwdStartTime).valueOf()
        let endTime = dayjs(formItem.pwdEndTime).valueOf()
        let params = {
          name: formItem.name,
          phonenumber: formItem.phone,
          country_code: formItem.country_code,
          permission_begin: startTime,
          permission_end: endTime,
          permission_status: 2,
          is_send_location: this.is_send_location,
          lease_id: this.linkTenant || null,
          password_type: 2
        }

        if (this.tenantLeaseId !== -1) {
          params.lease_id = this.tenantLeaseId
        }

        if (this.linkTenant) {
          params.password_type = 1
        }

        if (endTime - startTime < 5 * 60 * 1000) {
          this.$Message.error('时间过短')
          return
        }

        let apiObj
        let succTip = ''

        if (!this.sendOfflinePwd) {
          // 有网关锁
          apiObj = this.isForce ? api.password_has_tenant_send : api.password_send
          succTip = '在线密码'
        } else {
          apiObj = this.isForce ? api.password_has_tenant_send_active : api.password_send_active
          succTip = '离线密码'
          params.CMD = this.formItem.userGroup === 1 ? 1 : 2
        }

        // console.log('params请求参数==============》', params);

        http.request(this, apiObj, [this.lockDetail.roomId, this.lockDetail.id], params, (res, err) => {
          if (err || !res) {
            return
          }
          this.$Message.success(succTip + '放发成功')
          this.isVisible = false
        })
      })
    }, 300),

    resetForm (name) {
      this.$refs[name].resetFields()
    },

    onVisibleChange (v) {
      if (!v) {
        // this.formItem.pwdEndTime = '';
        this.is_send_location = false
        this.is_send_active_pwd = false
        this.resetForm('addPwdForm')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.pwd-padd {
    padding-bottom: 5px;
}
.add-pwd-room-info {
    display: flex;
    align-items: center;
    padding: 5px 0 10px 20px;
}
.add-pwd-line {
    border-bottom: 1px solid #ddd;
    margin: 0 0 10px;
    padding: 0 0 5px;
}
.add-pwd-pad {
    padding: 15px 0;
}
.add-pwd-label {
    text-align: right;
}
.add-pwd-cell {
    padding: 0 0 5px;
}
.add-pwd-form-item {
    margin-bottom: 10px;
}
</style>